import express, { Router, RequestHandler } from 'express';
import { auth } from '../middleware/auth';
import { authorize } from '../middleware/authorization';
import { asyncHandler } from '../middleware/asyncHandler';
import { ErrorLogController } from '../controllers/errorLogController';

const router: Router = express.Router();

// 所有路由都需要认证和管理员权限
router.use(auth as RequestHandler);
router.use(authorize(['admin']) as RequestHandler);

/**
 * @api {get} /api/error-logs/search 搜索错误日志
 * @apiName SearchErrorLogs
 * @apiGroup ErrorLog
 * @apiPermission admin
 * 
 * @apiQuery {String} [startDate] 开始日期
 * @apiQuery {String} [endDate] 结束日期
 * @apiQuery {String} [level] 日志级别 (ERROR|WARN|INFO)
 * @apiQuery {String} [code] 错误代码
 * @apiQuery {String} [severity] 严重程度
 * @apiQuery {Number} [page=1] 页码
 * @apiQuery {Number} [limit=20] 每页条数
 */
router.get(
  '/search',
  asyncHandler(ErrorLogController.searchLogs) as RequestHandler
);

/**
 * @api {get} /api/error-logs/stats 获取错误日志统计信息
 * @apiName GetErrorLogStats
 * @apiGroup ErrorLog
 * @apiPermission admin
 * 
 * @apiQuery {String} [startDate] 开始日期
 * @apiQuery {String} [endDate] 结束日期
 */
router.get(
  '/stats',
  asyncHandler(ErrorLogController.getStats) as RequestHandler
);

/**
 * @api {post} /api/error-logs/cleanup 清理过期错误日志
 * @apiName CleanupErrorLogs
 * @apiGroup ErrorLog
 * @apiPermission admin
 * 
 * @apiQuery {Number} [daysToKeep=30] 保留天数
 */
router.post(
  '/cleanup',
  asyncHandler(ErrorLogController.cleanupLogs) as RequestHandler
);

/**
 * @api {post} /api/error-logs/log 记录错误日志
 * @apiName LogError
 * @apiGroup ErrorLog
 * @apiPermission admin
 * 
 * @apiBody {Object} error 错误对象
 * @apiBody {Object} [metadata] 额外元数据
 */
router.post(
  '/log',
  asyncHandler(ErrorLogController.logError) as RequestHandler
);

export default router;
